﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors
{
    public partial class purchase : System.Web.UI.Page
    {
        private PagedDataSource _pagedDataSource = new PagedDataSource();
        
        private int _itemsPerPage = 5;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                #region Populate Controls
                PopulateCategoryDropDown();
                PopulateTimeSpanDropDown();
                #endregion

                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if(!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion

                #region Select filter data based on Query String
                if (Request.QueryString["category"] != null)
                {
                    ddlFilterCategory.SelectedValue = Request.QueryString["category"].ToString();
                }

                if (Request.QueryString["timespan"] != null)
                {
                    ddlFilterTimeSpan.SelectedValue = Request.QueryString["timespan"].ToString();
                }

                if (Request.QueryString["s"] != null)
                {
                    txtFilterSearch.Text = Request.QueryString["s"].ToString();
                }

                if (Request.QueryString["i"] != null)
                {
                    ddlResultsPerPage.SelectedValue = Request.QueryString["i"].ToString();
                }
                #endregion

                #region Bind Data
                if (Request.QueryString["i"] != null)
                {
                    _itemsPerPage = Convert.ToInt32(Request.QueryString["i"]);
                }

                BindDataList(_itemsPerPage);

                if (dlPurchaseResults.Items.Count == 0)
                {
                    lblNoResults.Visible = true;
                }
                #endregion

                #region Pagination
                CreatePagination();
                #endregion
            }
        }

        /// <summary>
        /// Populates the category dropdown list.
        /// </summary>
        private void PopulateCategoryDropDown()
        {
            List<Category> categories = dbExchange.GetAllCategories();

            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();
            
            if (categories.Count > 0)
            {
                ddlFilterCategory.DataSource = categories;

                if(!culture.Equals("en-GB"))
                    ddlFilterCategory.DataTextField = "CategoryName";
                else
                    ddlFilterCategory.DataTextField = "LocalizedCategoryName";

                ddlFilterCategory.DataValueField = "CategoryID";
                ddlFilterCategory.DataBind();

                ddlFilterCategory.Items.Insert(0, new ListItem("Vælg Kategori"));
            }
        }

        /// <summary>
        /// Populates the timespan dropdown list.
        /// </summary>
        private void PopulateTimeSpanDropDown()
        { 
            ListItem li1 = new ListItem("Alt", "0");
            ListItem li2 = new ListItem("1 uge", "7");
            ListItem li3 = new ListItem("1 måned", "30");
            ListItem li4 = new ListItem("3 måneder", "90");

            ddlFilterTimeSpan.Items.Add(li1);
            ddlFilterTimeSpan.Items.Add(li2);
            ddlFilterTimeSpan.Items.Add(li3);
            ddlFilterTimeSpan.Items.Add(li4);
        }

        /// <summary>
        /// Binds the datalist with purchases.
        /// </summary>
        /// <param name="itemsPerPage">Specifies the amount of sales to be shown per page.</param>
        private void BindDataList(int itemsPerPage)
        {
            int categoryId = 0;
            int timespan = Convert.ToInt32(ddlFilterTimeSpan.SelectedValue);
            string search = null;

            if (Request.QueryString["category"] != null)
            {
                categoryId = Convert.ToInt32(Request.QueryString["category"]);
            }

            if (Request.QueryString["timespan"] != null)
            {
                timespan = Convert.ToInt32(Request.QueryString["timespan"]);
            }

            if (Request.QueryString["s"] != null)
            {
                search = Request.QueryString["s"].ToString();
            }

            _pagedDataSource.DataSource = dbExchange.GetAllPurchases(timespan, categoryId, search);
            _pagedDataSource.AllowPaging = true;
            _pagedDataSource.PageSize = itemsPerPage;

            if (Request.QueryString["p"] != null)
            {
                _pagedDataSource.CurrentPageIndex = Convert.ToInt32(Request.QueryString["p"]) - 1;
            }
            else
            {
                _pagedDataSource.CurrentPageIndex = 0;
            }

            ViewState["TotalPages"] = _pagedDataSource.PageCount;

            dlPurchaseResults.DataSource = _pagedDataSource;
            dlPurchaseResults.DataBind();
        }

        /// <summary>
        /// Gets the QueryString.
        /// </summary>
        /// <returns>Returns a string containing the QueryString.</returns>
        public string GetQueryString()
        {
            NameValueCollection nvc = new NameValueCollection();

            if (ddlFilterCategory.SelectedIndex != 0)
            {
                nvc.Add("category", ddlFilterCategory.SelectedValue.ToString());
            }

            if (ddlFilterTimeSpan.SelectedIndex != 0)
            {
                nvc.Add("timespan", ddlFilterTimeSpan.SelectedValue.ToString());
            }

            if (txtFilterSearch.Text != String.Empty)
            {
                nvc.Add("s", txtFilterSearch.Text);
            }

            nvc.Add("i", ddlResultsPerPage.SelectedValue.ToString());

            if (Request.QueryString["p"] != null)
            {
                nvc.Add("p", Request.QueryString["p"].ToString());
            }
            else
            {
                nvc.Add("p", "1");
            }

            return GeneralTools.GenerateQueryString(nvc);
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            string url = Request.Path + GetQueryString();

            Response.Redirect(url);
        }

        //Event fired when the sale datalist is databound
        protected void dlPurchaseResults_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Separator)
            {
                Label lblDescription = (Label)e.Item.FindControl("lblPurchaseResultDescription");
                lblDescription.Text = GeneralTools.TruncateString(lblDescription.Text, 800, ".");

                HyperLink hyLinkPurchaseResultReadMore = (HyperLink)e.Item.FindControl("hyLinkPurchseResultReadMore");
                hyLinkPurchaseResultReadMore.Text = GetLocalResourceObject("hyLinkPurchseResultReadMoreText").ToString();
            }
        }

        /// <summary>
        /// Creates the pagination.
        /// </summary>
        private void CreatePagination()
        {
            if (Request.QueryString["p"] != null)
            {
                List<WebControl> links = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), Convert.ToInt32(Request.QueryString["p"]), Request.Url.Query, Request.Path);
                List<WebControl> links2 = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), Convert.ToInt32(Request.QueryString["p"]), Request.Url.Query, Request.Path);

                for (int i = 0; i < links.Count; i++)
                {
                    if (links[i] is HyperLink)
                    {
                        HyperLink link = (HyperLink)links[i];
                        HyperLink link2 = (HyperLink)links2[i];

                        panTopPagination.Controls.Add(link);
                        panPagination.Controls.Add(link2);
                    }

                    else if (links[i] is Label)
                    {
                        Label label = (Label)links[i];
                        Label label2 = (Label)links2[i];

                        panTopPagination.Controls.Add(label);
                        panPagination.Controls.Add(label2);
                    }    
                }
            }
            else
            {
                List<WebControl> links = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), 1, Request.Url.Query, Request.Path);

                List<WebControl> links2 = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), 1, Request.Url.Query, Request.Path);

                for (int i = 0; i < links.Count; i++)
                {
                    if (links[i] is HyperLink)
                    {
                        HyperLink link = (HyperLink)links[i];
                        HyperLink link2 = (HyperLink)links2[i];

                        panTopPagination.Controls.Add(link);
                        panPagination.Controls.Add(link2);
                    }

                    else if (links[i] is Label)
                    {
                        Label label = (Label)links[i];
                        Label label2 = (Label)links2[i];

                        panTopPagination.Controls.Add(label);
                        panPagination.Controls.Add(label2);
                    }    
                }
            }
        }

        //Event fired when the selected index of the result per page dropdown list has changed
        protected void ddlResultsPerPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            string url = Request.Path + GetQueryString();

            Response.Redirect(url);
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            btnFilter.Text = GetLocalResourceObject("btnFilterText").ToString();
            hyLinkCreatePurchase.Text = GetLocalResourceObject("hyLinkCreatePurchaseText").ToString();
            lblFilterCategory.Text = GetLocalResourceObject("lblFilterCategoryText").ToString();
            lblFilterHeader.Text = GetLocalResourceObject("lblFilterHeaderText").ToString();
            lblFilterSearch.Text = GetLocalResourceObject("lblFilterSearchText").ToString();
            lblFilterTimeSpan.Text = GetLocalResourceObject("lblFilterTimeSpanText").ToString();
            lblResultsPerPage.Text = GetLocalResourceObject("lblResultsPerPageText").ToString();
            ddlFilterCategory.Items[0].Text = GetLocalResourceObject("ddlCategoryDummyObjectText").ToString();
            ddlFilterTimeSpan.Items[0].Text = GetLocalResourceObject("ddlTimeSpanDummyObjectText").ToString();
            lblNoResults.Text = GetLocalResourceObject("lblNoResultsText").ToString();
        }
    }
}